#! -*- coding: utf-8 -*-
"""
oraclesrv
"""

import os
import logging
import cx_Oracle
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'


LOG = logging.getLogger("engine.oracle")


class OracleSrv(object):
    """ OracleSrv """
    def __init__(self, host, port, user, pwd, db):
        self.host = host
        self.port = port
        self.user = user
        self.pwd = pwd
        self.dateb = db

        self.conn = None
        self.cur = None

    def __del__(self):
        self.close()

    def close(self):
        """
        关闭连接
        """
        if self.conn:
            self.conn.close()
            self.conn = None
            self.cur = None

    def _initconnect(self):
        """
        init connect
        """
        if not self.dateb:
            raise(ValueError, r"没有设置数据库信息")

        LOG.info("connect oracle %s %s %s %s", \
            self.host, self.port, self.user, self.dateb)
        url = "%s:%s/%s" % (self.host, self.port, self.dateb)
        self.conn = cx_Oracle.connect(self.user, self.pwd, url)
        self.cur = self.conn.cursor()

        if not self.cur:
            raise(ValueError, r"连接数据库失败")

    def _getconnect(self):
        """
        得到连接信息
        返回: conn.cursor()
        """
        if not self.cur:
            self._initconnect()
        return self.cur

    def exec_query(self, sql):
        """
        exec_query
        """
        cur = self._getconnect()
        LOG.info("oracle %s exec %s", self.dateb, sql)
        cur.execute(sql)
        ret_list = cur.fetchall()
        return ret_list

    def exec_nonquery(self, sql):
        """
        exec_nonquery
        """
        cur = self._getconnect()
        LOG.info("oracle %s exec %s", self.dateb, sql)
        cur.execute(sql)
        self.conn.commit()
